﻿using WebOS.Bll;
using WebOS.Modle;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Principal;
using System.Threading.Tasks;
using Asxsyd92Core.Utils;
using IdentityModel;
using Asxsyd92Core.Utils.Data.SQLServer;
// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace WebOSCore.Controllers.Api
{

    public class UsersController : Controller
    {
        [Route("api/Users/GetUsersTreeAsync")]

        [HttpGet]
        [Authorize]
        public string GetUsersTreeAsync()
        {
            //  var user = await _userManager.GetUserAsync(HttpContext.User);

            var da = UsersBll.Instance.GetUsersList("", "", 0, 0);
            //查找组织架构

            var q = from p in da group p by p.Organize into g select new { name = g.Key, id = g.First().OrganizeID.ToString(), children = g.Where(p => p.Organize == g.Key).ToList() };

            return Asxsyd92Core.Utils.JSONhelper.ToJson(new { code = 0, msg = "", data = q }, false);
        }

        [Route("api/Users/GetUsersList")]

        [HttpGet]
        [Authorize]
        public string GetUsersListAsync()
        {
            //  var user = await _userManager.GetUserAsync(HttpContext.User);

            var da = UsersBll.Instance.GetUsersList("", "", 0, 100);
            var name = User.Identity.Name;
            var isAuthenticated = User.Identity.IsAuthenticated;
            var id = User.Claims.FirstOrDefault(c => c.Type == "id").Value;
            Guid guid;
            Guid.TryParse(id, out guid);
            var my = da.First(c => c.ID == guid);
            Mine mine = new Mine();
            mine.username = my.Name;
            mine.avatar = "http://cdn.firstlinkapp.com/upload/2016_6/1465575923433_33812.jpg";
            mine.id = my.ID.ToString();
            mine.sign = my.Organize;
            mine.status = "1";
            //查找组织架构

            var q = from p in da group p by p.Organize into g select new FriendItem { groupname = g.Key, id = g.First().OrganizeID.ToString(), online = 1, list = g.Where(p => p.Organize == g.Key).ToList() };
            List<object> list = new List<object>();
            list.Add(new { mine = mine, friend = q, group = "" });
            return Asxsyd92Core.Utils.JSONhelper.ToJson(new { code = 0, msg = "", count = da.Count == 0 ? 0 : da.First().Count, data = list[0] }, false);
        }

        [Route("api/Users/GetAppList")]

        [HttpPost]
        [Authorize]
        public string GetAppList()
        {
            var Role = User.Claims.FirstOrDefault(c => c.Type == "http://schemas.microsoft.com/ws/2008/06/identity/claims/role").Value;
            // Guid guid;
            int role = 0;
            //Guid.TryParse(id, out guid);
            int.TryParse(Role, out role);
            return RoleAppBll.Instance.GetAppList(role);

        }

        [Route("api/Users/GetAppDektop")]

        [HttpPost]
        [Authorize]
        public string GetAppDektop()
        {
            var name = User.Identity.Name;
            var isAuthenticated = User.Identity.IsAuthenticated;
            var id = User.Claims.FirstOrDefault(c => c.Type == "id").Value;
            Guid guid;
            Guid.TryParse(id, out guid);
            return RoleAppBll.Instance.GetAppDektop(guid);

        }
        [Authorize]
        [HttpGet]
        [Route("api/Users/GetToMenu")]

        public string GetToMenu()
        {
            return RoleAppBll.Instance.GetAllApp();
        }
        [Authorize]
        [HttpGet]
        [Route("api/Users/GetSetMenu")]
        public string GetSetMenu(int v)
        {
            return RoleAppBll.Instance.GetSetMenu(v);
        }
        [HttpPost]
        [Authorize]
        [Route("api/Users/SetRole")]
        public string SetRole(int key, string list)
        {
            var da = list.Split(',');
            //全部删除然后添加
            WebOS.Dal.UsersRoleDal.Instance.Delete(new { identifier = key });
            foreach (var item in da)
            {

                var u = WebOS.Dal.UsersRoleDal.Instance.Get(new { MenuID = item.ToGuid(), identifier = key });
                if (u == null)
                {

                    UsersRole role = new UsersRole();
                    role.ID = Guid.NewGuid();
                    role.identifier = key;
                    role.MenuID = item.ToGuid();
                    WebOS.Dal.UsersRoleDal.Instance.Insert(role);
                }


            }
            return Newtonsoft.Json.JsonConvert.SerializeObject(new { msg = "操作成功！", Success = true });
        }
        [Route("api/Users/AddMenu")]
        [HttpPost]
        [Authorize]
        public string AddMenu(string data)
        {

            try
            {
                //根据用户获取待办
                var id = User.Claims.FirstOrDefault(c => c.Type == "id").Value;
                //根据用户获取待办
                //     var Role = User.Claims.First(c => c.Type.IndexOf("ole") > 0).Value;
                var name = User.Identity.Name;
                WebOS.Modle.RoleApp art = Newtonsoft.Json.JsonConvert.DeserializeObject<WebOS.Modle.RoleApp>(data);
                if (art != null)
                {

                    return RoleAppBll.Instance.AddMenu(art);
                }
            }
            catch (Exception ex) { var mas = ex.Message; }
            return Newtonsoft.Json.JsonConvert.SerializeObject(new { msg = "发生异常错误，请联系管理员！", Success = false });

        }
        [HttpPost]
        [Route("api/Users/DelMenu")]
        [Authorize]
        public string DelMenu(Guid ID)
        {
            return RoleAppBll.Instance.DelByID(ID);
        }
        [Route("api/Users/GetUser")]
        [HttpGet]
        [Authorize]
        public string GetUserList()
        {
            var da = WebOS.Dal.UsersDal.Instance.GetAll();
            return Asxsyd92Core.Utils.JSONhelper.ToJson(new { code = 0, msg = "", count = da.Count(), data = da }, false);
        }

        /// <summary>
        /// 获取菜单
        /// </summary>
        /// <returns></returns>
        [Route("api/Users/GetDictionary")]

        [HttpGet]
        // [Authorize]
        public string GetDictionary(long page = 1, long limit = 15)
        {
            return DictionaryBll.Instance.GetDictionary(page, limit);

        }
        [Route("api/Users/GetByCode")]
        [HttpGet]
        [Authorize]
        public string GetByCode(string code)
        {

            return WebOS.Bll.DictionaryBll.Instance.GetByCode(code);

        }
        [HttpPost]
        [Authorize]
        [Route("api/User/EditPw")]

        public string EditPw(string old, string pw)
        {
            var user = User.Claims.FirstOrDefault(c => c.Type == JwtClaimTypes.NickName).Value;
            var ps = Asxsyd92Core.Utils.Tools.MD5System(Asxsyd92Core.Utils.Tools.EncryptionPassword(user) + Asxsyd92Core.Utils.Tools.EncryptionPassword(old));
            var Role = User.Claims.FirstOrDefault(c => c.Type == "http://schemas.microsoft.com/ws/2008/06/identity/claims/role").Value;
          
                var us = UsersBll.Instance.Login(user);
                if (us.Password != ps)
                {
                    return JSONhelper.ToJson(new { msg = "原密码错误！", Success = false });
                }
                else
                {
                    us.Password = Asxsyd92Core.Utils.Tools.MD5System(Asxsyd92Core.Utils.Tools.EncryptionPassword(user) + Asxsyd92Core.Utils.Tools.EncryptionPassword(pw)); ;

                    if (WebOS.Dal.UsersDal.Instance.Update(us) > 0)
                    {
                        return JSONhelper.ToJson(new { msg = "修改成功！", Success = true });
                    };
                    return JSONhelper.ToJson(new { msg = "修改失败，请使用原密码登录！", Success = false });
                }

        }
        [Authorize]
        [HttpGet]
        [Route("api/User/UserList")]
        public string UserList(string title, string decs = "ID", int page = 1, int limit = 15)
        {
            var o = UsersBll.Instance.GetUsers(title, decs, page, limit);
            if (o.FirstOrDefault() != null)
            {

                var os = Models.Unity.ObjModel(o.FirstOrDefault());
                return Asxsyd92Core.Utils.JSONhelper.ToJson(new
                {
                    code = 0,
                    msg = "",
                    count = os.FirstOrDefault(c => c.Key.ToString() == "Count").Value,
                    data = o
                });
            }
            return Asxsyd92Core.Utils.JSONhelper.ToJson(new { code = 0, msg = "", count = 0, data = o });
        }
        [Authorize]
        [HttpPost]
        [Route("api/Users/UsersSave")]
        public string UsersSave(string data) {
            data = Models.Unity.OperationJson(data);
            var ter = Newtonsoft.Json.JsonConvert.DeserializeObject<Users>(data);
            if (ter != null)
            {
                //新增初始化密码
                if (ter.ID == Guid.Empty)
                {
                    //检查帐号是否重复
                    var us = WebOS.Dal.UsersDal.Instance.Get(new { Account = ter.Account.ToLower() }); //SqlFromData.GetFromData("S_Teacher", new { S_Account = ter["S_Account"].ToString().ToLower() }).FirstOrDefault();
                    if (us != null)
                    {
                        return JSONhelper.ToJson(new { msg = "系统中存在相同帐号，请更换账号再试！", Success = false });
                    }

                    //获取配置中的密码
                    var pw = Asxsyd92Core.Utils.Provider.AppSetting.GetConfig("ConfigPassword");//ter["S_PW"].ToString();
                    var account = ter.Account.ToString();
                    var ps = Asxsyd92Core.Utils.Tools.MD5System(Asxsyd92Core.Utils.Tools.EncryptionPassword(account.ToString().ToLower()) + Asxsyd92Core.Utils.Tools.EncryptionPassword(pw));
                    ter.Password = ps;
                    ter.Account = ter.Account.ToLower();
                    ter.ID = Guid.NewGuid();
                    var id = WebOS.Dal.UsersDal.Instance.Insert(ter);
                    if (id > 0)
                    {
                        
                          var ors=  WebOS.Dal.UsersRelationDal.Instance.Get(new { OrganizeID= ter.OrganizeID, ID = ter.ID });
                        if (ors == null)
                        {
                            UsersRelation usersRelation = new UsersRelation();
                            usersRelation.OrganizeID = ter.OrganizeID;
                            usersRelation.ID = ter.ID;
                            usersRelation.IsMain = 1;
                            usersRelation.Sort = 1;
                            WebOS.Dal.UsersRelationDal.Instance.Insert(usersRelation);
                        }
                        else {
                            ors.OrganizeID = ter.OrganizeID;
                            WebOS.Dal.UsersRelationDal.Instance.Update(ors);
                        }
                        return JSONhelper.ToJson(new { msg = "添加失败！", Success = true });
                    }
                    else { return JSONhelper.ToJson(new { msg = "添加失败！", Success = false }); }
                }
                else
                {
                    var ks = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<object, object>>(data);
                   if (ks == null) {
                        return JSONhelper.ToJson(new { msg = "数据解析失败！", Success = false });
                    }
                    ks["Account"] = ks["Account"].ToString().ToLower();
                            var iss = SqlFromData.SaveFromData("Users", ks.ToJson());
                    if (iss == Guid.Empty)
                    {
                        return JSONhelper.ToJson(new { msg = "添加失败！", Success = false });
                    }
                    else
                    {
                        var ors = WebOS.Dal.UsersRelationDal.Instance.Get(new { OrganizeID = ks["OrganizeID"].ToString().ToGuid(), ID = iss });
                        if (ors == null)
                        {
                            UsersRelation usersRelation = new UsersRelation();
                            usersRelation.OrganizeID = ter.OrganizeID;
                            usersRelation.ID = Guid.NewGuid();
                            usersRelation.UserID = ter.ID;
                            usersRelation.IsMain = 1;
                            usersRelation.Sort = 1;
                            WebOS.Dal.UsersRelationDal.Instance.Insert(usersRelation);
                        }
                        else
                        {
                            ors.OrganizeID = ter.OrganizeID;
                            ors.UserID = ter.ID;
                            
                            WebOS.Dal.UsersRelationDal.Instance.Update(ors);
                        }
                        return JSONhelper.ToJson(new { msg = "添加成功！", Success = true });

                    }
                }
       
            }
            else { return JSONhelper.ToJson(new { msg = "数据解析失败！", Success = false }); }

        }
        //获取部门和角色
        [Authorize]
        [HttpGet]
        [Route("api/Users/OrganizeAndRole")]
        public string OrganizeAndRole()
        {
           var data= SqlFromData.GetList("SELECT ID,Name ,'1' as type,3 AS identifier FROM Organize UNION ALL SELECT ID, Name, '0' as type,identifier FROM Role").ToList();
         
            return JSONhelper.ToJson(new { msg = "1部门，0角色" ,data=data }); 
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="key"></param>
        /// <param name="table"></param>
        /// <returns></returns>
        [Authorize]
        [HttpPost]
        [Route("api/Users/DicDel")]
        public string DicDel(Guid key)
        {
            return WebOS.Bll.DictionaryBll.Instance.Delte(key);
        }
    }
}
